<template>
<div class="add-graph-left">
    <Spin size="large" fix v-if="loading"></Spin>
    <div class="left fix-scrollbar">
        <div class="text-center m-b-10 m-t-10">
            <RadioGroup v-model="leftMenuShow" type="button" size="small" class="close-group">
                <Radio label="数据属性"></Radio>
                <Radio label="图形属性"></Radio>
            </RadioGroup>
        </div>
        <div class="datasoure" v-show="leftMenuShow==='数据属性'">
            <div class="title">所属指标目录</div>
            <div>
                <Input v-model="catalogType.catalogName" readonly></Input>
            </div>
            <div class="title">业务指标【拖曳至配置区】</div>
            <ul class="tablefield">
                <li v-for="(item,index) in indexList" :key="index"
                        draggable="true"
                        @dragstart="moveStart(item,$event)"
                        @dragend="moveEnd(item,$event)">
                    <i class="fa active-color"  :class="{'zlstbd-icon-text':item.kpiType =='1','zlstbd-icon-numerical-value':item.kpiType==='2',
                        'zlstbd-icon-date': item.kpiType==='3'}"></i>
                    {{item.kpiName}}
                </li>
                <div v-if="indexList.length == 0 " class="title p-t-30 text-center">请选择业务指标</div>
            </ul>
        </div>
        <div class="graph-style fix-scrollbar" v-show="leftMenuShow==='图形属性'">
          <add-graph-right ref="graphOptions" v-if="componentState.rightMenuState"
            :initdata="graphInfo"
            :initoptions="initoptions"
            :graph-chart-list="graphChartList"
            :graph-type="graphType"
            @changeType="changeType"
            @changeOptions="changeOptions"
            :graph-options="graphOptions"
            :groups="groups"
            :numbers="numbers" >
          </add-graph-right>
        </div>
    </div>
    <div class="content">
        <div class="scorller-cnt">
            <div class="graph-column">
                <div id="groups" class="column-group" >
                    <div class="title f-l">
                        <span class="rounds"></span>
                        <span class="f-l">维度</span>
                    </div>
                    <div class="f-l">
                        <zl-select class="zl-dropdown-group" :init="groups" :menu="groupMenus" value="dimeName" @on-change="dimensionChange"></zl-select>
                    </div>
                </div>
                <div id="nums" class="column  m-b-10" @drop='dropEv($event)' @dragover='allowDrop($event)' >
                    <div class="title f-l">
                        <span class="rounds"></span>
                        <span>数值</span>
                    </div>
                    <ul class="">
                        <li v-for="(item,index) in numbers" :key="index" draggable="true"   @dragstart="cloumnMoveStart('nums',index,$event)">
                            <column-menu :groupOptions="dataTypeInfo.int.indexOf(item.dataType)!=-1?numOptions:textOptions" v-model="numbers[index]" >
                                <span class="cloumntit">{{item.kpiName}}
                                </span>
                                <span slot="last" class="pointer close" @click="removeNums(index)"> <i class="zlstbd-icon-delete"></i></span>
                            </column-menu>
                        </li>
                    </ul>
                </div>
            </div>

            <div class="graph-content">
                <div class="graph-chart"  >
                    <graph-panel  :paneltype="'edit'" ref="graphpanel" :graph-type="graphType" :datasource="panaledatasource" :graph-options="graphOptions" ></graph-panel>
                </div>
            </div>

        </div>
    </div>
</div>
</template>

<script>
import getData from 'getData'
import graphFilter from './graph-filter'
import addGraphRight from './add-graph-right'
import ColumnMenu from '@/components/common/group-menu'
import graphPanel from '@/components/panels/graph-panel'
import ZlSelect from '@/components/common/zl-select'
import DimensionValue from '@/components/graph/dimension-value';
import util from 'util'
export default {
    name: 'addGraphLeft',
    components:{ColumnMenu, graphFilter,graphPanel,addGraphRight, ZlSelect, DimensionValue},
    data () {
        return {
            loading:false,
            //组件初始化数据加载完成之后再渲染组件内容
            componentState:{
                rightMenuState:false
            },
            //数据属性   图形属性 切换
            leftMenuShow:'数据属性',
            //可以选择的图形集合
            graphChartList:[],
            //选择的图表 类型
            graphType:'',
            //数值
            numbers:[],
            //维度
            groups:[],
            groupNumLock:false,
            //条件筛选
            conditions:[],
            datasource:{
                datasourceId:'',
                tableName:'',
                datasourceType:'',
                projectId:''
            },
            //元件基本信息 编辑回显
            graphInfo:{},
            datasourceList: [],//数据源列表
            tableFieldList:[],//表格列表
            moveItem:{},
            moveType:'',
            dataTypeInfo:{
                int:'int,float,double',
                data:'date,timestamp'
            },
            //图表基础设置
            graphOptions: {
                legend: {
                  show: true,
                  top: '34',
                  textStyle: {
                    color: '#333'
                  }
                },
                tooltip: {},
                dataset: {},
                xAxis: [
                    {
                        type: 'category',
                        show:true,
                        onZeroAxisIndex :0,
                        axisLine: {
                            onZero: false,
                            lineStyle: {
                                width: 1,
                                color: '#333',
                                type: 'solid'
                            }
                        },
                        splitLine: {
                          show: false,
                          lineStyle: {
                            color: '#ddd',
                            width: 1,
                            type: 'solid'
                          }
                        },
                        axisLabel :{
                            rotate : '0',
                            // fontFamily : 'SimSun',
                            // color: '#409EFF',
                            fontSize : '12',
                            // formatter: function (value, index) {
                            //     return   value.indexOf('_')==-1?value:value.substring(0,value.indexOf('_'));
                            // }
                        },
                    }],
                yAxis: [
                  {
                    show: true,
                    axisLine: {
                        lineStyle: {
                            width: 1,
                            color: '#333',
                            type: 'solid'
                        }
                    },
                    splitLine: {
                      show: false,
                      lineStyle: {
                        color: '#ddd',
                        width: 1,
                        type: 'solid'
                      }
                    },
                    axisLabel :{
                        rotate : '0',
                        // fontFamily : 'SimSun',
                        // color: '#409EFF',
                        fontSize : '12',
                        // formatter: function (value, index) {
                        //     return   value.indexOf('_')==-1?value:value.substring(0,value.indexOf('_'));
                        // }
                    }
                  }
                ],
                series: [],
                title:{
                    text: '',
                    x: 'left',
                    padding: [16, 20],
                    textStyle: {
                      color: '#333',
                      fontSize: '14'
                    }
                },
                others: {} // 用于非echart传数据
            },
            initoptions:{},
            groupOptions:[
                {
                    value:'sort',
                    options:[
                        {value: 'ASC',label: '升序'},
                        {value: 'DESC',label: '降序'},
                    ]
                }
            ],
            numOptions:[
                {
                    value:'aggregation',
                    options:[
                        {value: 'SUM',label: '求和'},
                        {value: 'AVG',label: '平均值'},
                        {value: 'COUNT',label: '计数'},
                        {value: 'COUNT_DISTINCT',label: '去重计数'},
                        {value: 'MAX',label: '最大值'},
                        {value: 'MIX',label: '最小值'}
                    ]
                },
                {
                    value:'sort',
                    options:[
                        {value: 'ASC',label: '升序'},
                        {value: 'DESC',label: '降序'},
                    ]
                }
            ],
            textOptions:[
                {
                    value:'aggregation',
                    options:[
                        {value: 'COUNT',label: '计数'},
                        {value: 'COUNT_DISTINCT',label: '去重计数'},
                    ]
                },
                {
                    value:'sort',
                    options:[
                        {value: 'ASC',label: '升序'},
                        {value: 'DESC',label: '降序'},
                    ]
                }
            ],
            groupsList: [],
            groupsSel: ['date', 'min_temp'],
            catalogType: {},
            optionsDir: [],
            catalogDir: null,
            indexList: [],
            isNumberChange: false,
            groupMenus: [],
            catalogList: [],
            isManiImageAttr: true
        }
    },
    watch:{
        numbers:  {
            handler(newValue, oldValue) {
                this.judgeGraphType();
    　　　　},
    　　　　deep: true
    　　},
        groups:{
            handler(newValue, oldValue) {
                this.judgeGraphType();
    　　　　},
    　　　　deep: true
        }
    },
    computed:{
        panaledatasource(){
            var source={};
            source.datasourceId=this.datasource.datasourceId;
            source.datasourceType=this.datasource.datasourceType;
            source.tableName=this.datasource.tableName;
            source.groups=this.groups;
            source.numbers=this.numbers;
            source.conditions=this.conditions;
            source.isNumberChange = this.isNumberChange
            return source;
        }
    },
    methods:{
      dimensionChange(dimensions) {
        this.isNumberChange = false
        this.groups = dimensions
      },
      // 获取维度
      getDimension() {
        let kpiCode = ''
        for (let i = 0; i < this.numbers.length; i++) {
          const num = this.numbers[i];
          if (i === 0) {
            kpiCode += num.kpiCode
          } else {
            kpiCode += ',' + num.kpiCode
          }
        }
        getData.get('findDimeByKpiCode', {
          params: {kpiCode}
        }).then((result) => {
          if (result.data && result.data.resultCode === 0) {
            this.groupMenus = result.data.data
          }
        }).catch((err) => {

        });
      },
      // 获取指标目录下的所有业务指标
      getIndexsByCatalogDir(catalogDirId) {
      	getData.get('findByKpiTypeAndCatalogId', {
          params: {
            kpiType: 'BUSI',
            catalogId: catalogDirId
          }
        }).then((result) => {
          if (result.data && result.data.resultCode === 0) {
            this.indexList = result.data.data
          }
        })
      },
      getIndexDirById(indexArr, dirArr, id) {
        for (let i = 0; i < indexArr.length; i++) {
          const index = indexArr[i];
          if (index.id === id) {
            dirArr.push(index.label)
            return dirArr
          } else if (index.children) {
            dirArr.push(index.label)
            return this.getIndexDirById(index.children, dirArr, id)
          }
        }
      },
      // 指标目录选择
      indexDirSelect(leaf) {
        this.getIndexsByCatalogDir(leaf.id)
        // 保存目录
        this.catalogList = this.getIndexDirById(this.optionsDir, [], leaf.id)
      },
        init(){
            this.initoptions =util.util.cloneObj(this.graphOptions);
            // this.initDatasources();
            // console.log('this.catalogType is ', this.catalogType)
            this.getIndexsByCatalogDir(this.catalogType.catalogId)
            this.initEditInfo();
        },
        //初始化查询指标目录
        initDatasources() {
            getData.getExpend('queryCatalog', 'findCatByCatType', this.catalogType.catalogType).then((result) => {
              if (result.status === 200 && result.data.resultCode === 0) {

                this.optionsDir = util.util.exchangeTree(result.data.data)
              }
            })
            this.datasource.projectId =this.$route.query.projectId;
        },
        //数据初始化 编辑  数据图表回显
        initEditInfo(){
          let vm = this
            var route =this.$route.query;
            if(route.id!=null  &&route.id !=''){
              // 编辑
                vm.loading=true;
                getData.get('getGraph',{},route.id).then(res=>{
                    if(res.status == 200 && res.data.code == '000'){
                        var graphInfo =res.data.data;
                        vm.groupNumLock =true;
                        var datasource =JSON.parse(graphInfo.datasource);
                        vm.groups=datasource.groups;
                        vm.numbers =datasource.numbers;

                        vm.$nextTick(()=>{
                            vm.graphOptions =JSON.parse(graphInfo.graphOptions);
                            vm.conditions =datasource.conditions;
                            util.util.extendObj(vm.datasource ,datasource)
                            vm.datasource.projectId =graphInfo.projectId;
                            vm.queryColumns();
                            //图表基础属性  赋值 数据回显
                            vm.graphType =graphInfo.graphType;
                            vm.graphInfo.graphName=graphInfo.graphName;
                            vm.graphInfo.graphTag=graphInfo.graphTag;
                            vm.graphInfo.remark=graphInfo.remark;
                            vm.graphInfo.access=graphInfo.access;
                            vm.graphInfo.graphId=graphInfo.graphId;
                            vm.componentState.rightMenuState =true;
                            vm.loading=false;
                            vm.groupNumLock =false;
                            vm.getDimension()
                        })
                    }else{
                        vm.$Message.error('请求错误，请检查网络');
                    }
                })
            }else{
                vm.componentState.rightMenuState =true;
            }
        },
        //返回到外层组件   图表属性
        getDataSoure(){
            var info =this.$refs.graphOptions.getGraphInfo();
            var result ={
                datasource:this.panaledatasource,
                graphUrl:this.$refs.graphpanel.getDataURL(),
                graphType:this.graphType,
                graphOptions:this.graphOptions,
                groups:this.groups,
                numbers:this.numbers,
                // datasourceId:this.datasource.datasourceId,
                // classficationId:this.catalogType.catalogType
                classficationId:this.catalogType.catalogId
            }
            return util.util.extendObj(result,info);
        },

        //改变图表样式
        changeOptions(item){
            var newvalue;
            console.log('changeOptions', item)
            if(item.key !=null){
                if(item.key=='xAxis'){
                    newvalue =util.util.cloneObj(this.graphOptions[item.key]);
                    util.util.extendObj(newvalue[0],item.value);
                }else{
                  // 进入其他 others 图表类型
                  newvalue = util.util.cloneObj(this.graphOptions[item.key]);
                  util.util.extendObj(newvalue,item.value);
                }
                var options = util.util.cloneObj(this.graphOptions)
                options[item.key]= newvalue
                this.graphOptions= options;
            }else{
                this.graphOptions= item;
            }
        },
        changeType(type){
            this.graphType =type;
        },
        //判断当前维度  支持的  图表类型
        judgeGraphType(){
            //只有一个维度
            var types =[];
            //table  表格展示
            //tree
            var type ='';
            if(this.groups.length>0|| this.numbers.length>0){
                types.push('table');
                types.push('text');
                types.push('img');
                type ='pie';
            }
            if(this.groups.length==2 && this.numbers.length==0){
                types.push('bar');//柱状图
                types.push('bar_type');//条形图
                types.push('line');//折线图
                type ='bar';
            }
            if(this.groups.length==0 && this.numbers.length==1){
                types.push('gauge');//计量图
            }

            if(this.groups.length<=2 && this.numbers.length>=1){
                types.push('bar');//柱状图
                types.push('bar_type');//条形图
                types.push('pie_more');
                type ='bar';
            }
            if(this.groups.length>0 &&this.groups.length<=2 && this.numbers.length>=1){
                types.push('line');//折线图
                types.push('line_area');//面积图
                type ='line';
            }
            if(0<this.groups.length&& this.groups.length<=2 && this.numbers.length>=2){
                types.push('bar_pile');//柱状堆叠图
                types.push('bar_type_pile');//条形堆叠图
                // types.push('bar_pile_percent');//柱状堆叠百分比图
                // types.push('bar_type_pile_percent');//条形堆叠百分图
            }
            if(this.groups.length==1 && this.numbers.length==2){
                types.push('scatter');//散点
            }
            if(this.groups.length==1 && this.numbers.length==0){
                types.push('pie');//
            }
            if((this.groups.length==1 && this.numbers.length==1)||(this.groups.length==0&& this.numbers.length>=1)){
                types.push('pie');//饼图  出现多个维度的时候，为环形饼图
                types.push('funnel');//漏斗图
            }
            if(this.groups.length>=2 && this.numbers.length==1){
                // types.push('pie_more');//嵌套环形饼图  出现多个维度的时候，为环形饼图
            }
            if(this.groups.length>=1 && this.numbers.length<=1){
                types.push('tree');//树图
            }
            if(this.groups.length==1 && this.numbers.length>=1){
                types.push('map');
            }
            if (this.groups.length >= 0 && this.numbers.length === 1) {
              types.push('card');
            }
            // this.$set(this.$parent,'graphChartList',types)
            // 当前维度  支持可以选择的图表类型集合
            this.graphChartList =types;
            // this.$emit("changeTypes",types);
            //在当前可以选择的 图表类型  当前默认选择的图表类型
            if(this.groupNumLock){
                return ;
            }
            this.graphType=type;
            console.log(2)
            // this.$emit("changeType",type);
        },
        //字段  拖拽
        moveStart(item,ev){
            this.moveItem =item;
            this.moveType='table';
        },
        //数值和维度 拖拽
        cloumnMoveStart(type,index,ev){
            this.moveType='cloumn';
            ev.dataTransfer.setData("index",index);
            ev.dataTransfer.setData("moveType",type);
        },
        //拖拽结束 筛选条件  过滤
        dropFilter(ev){
            var temp =util.util.cloneObj(this.conditions);
            var item = util.util.cloneObj(this.moveItem);
            item.list=[];
            temp.push(item);
            this.conditions=temp;
            // this.conditions.push(item);
            // console.log('cpush',this.conditions,temp)
        },
        //拖拽 结束 并且落在规定载体里面
        dropEv(ev){
            var cloum ,index=-1,$dom,$cloum;
            for(var i=0;i<ev.path.length;i++){
                if(ev.path[i].id=='nums'){
                    cloum="nums";
                    $cloum=ev.path[i];
                }else if(ev.path[i].id=='groups'){
                    cloum='groups';
                    $cloum=ev.path[i];
                }
                if( ev.path[i].className ==='group-menu'){
                    $dom=ev.path[i];
                }
            }
            if($dom!=null){
                var $list =$cloum.querySelectorAll('.group-menu');
                for(var i =0 ;i<$list.length;i++){
                    if($list[i]==$dom){
                        index=i+'';
                    }
                }
            }

            this.isNumberChange = false
            if(this.moveType==='table'){
                //1左侧  字段  新增
                var item =util.util.cloneObj(this.moveItem);
                // console.log('item: ', item)
                if(cloum=='nums'){
                  // 数值新增
                    // if(this.dataTypeInfo.int.indexOf(item.dataType)!=-1){
                    //     item.aggregation="SUM";
                    //     item.aggregationName="求和";
                    // }else {
                    //     item.aggregation="COUNT";
                    //     item.aggregationName="计数";
                    // }
                    if(util.util.getArrayObjectByValues(this.numbers,item,'kpiName')==null){
                      if (this.groups.length === 0) {
                        this.isNumberChange = true
                      }
                      this.numbers.push(item);
                      this.getDimension()
                    }else{
                        this.$Message.error('该字段已经在筛选列表里，请勿重复添加')
                    }
                }else if(cloum=='groups'  && this.groups.length<2){
                  // 分组
                    if(util.util.getArrayObjectByValues(this.groups,item,'kpiName')==null){
                        this.groups.push(item);
                    }else{
                        this.$Message.error('该字段已经在筛选列表里，请勿重复添加')
                    }
                }
            }else if(this.moveType ==='cloumn'){
                //2维度和数据   改变位置
                var moveIndex =ev.dataTransfer.getData("index");
                var mtype  =ev.dataTransfer.getData("moveType");
                if( mtype==cloum && moveIndex!==index){
                    var list =cloum=='nums'?this.numbers:this.groups;
                    if(index<0){//没有选择
                        index=list.length-1;
                    }
                    var good=list[moveIndex];
                    var goodo=list[index];
                    list.splice(moveIndex,1,goodo);
                    list.splice(index,1,good);
                }
            }
        },
        moveEnd(){
            this.moveItem ={};
            this.moveType='';
        },
        allowDrop(ev){
            ev.preventDefault();
        },
        removeGroup(index){
            this.groups.splice(index,1)
        },
        removeNums(index){
          this.isNumberChange = true
          this.numbers.splice(index,1);
          this.getDimension()
        },

        //改变数据源   查询当前数据源的列字段数据集
        queryColumns(value) {
            var datas =util.util.getArrayObjectByValues(this.datasourceList,{datasourceId:this.datasource.datasourceId},'datasourceId');
            if(datas!=null){
                this.datasource.datasourceType =datas.datasourceType;
                this.datasource.tableName =datas.tableName;
                var datasource = this.datasource;
                if (this.datasource.datasourceId != '') {
                    getData.get('queryDatasourceColumns', {},this.datasource.datasourceId).then((res) => {
                        if (res.status == 200 && res.data.code == '000') {
                            this.tableFieldList =res.data.data;
                            // TODO: 写死用做维度
                            if (res.data.data && res.data.data.length > 0) {
                                this.groupsList = res.data.data
                            }
                        }
                    });
                }
            }else{
                var y =setInterval(()=>{
                    var datas =util.util.getArrayObjectByValues(this.datasourceList,{datasourceId:this.datasource.datasourceId},'datasourceId');
                    if(datas!=null){
                        this.queryColumns();
                        clearInterval(y);
                    }
                },1000)
            }

        },
    },
    mounted(){
      this.catalogType = {
        catalogTypeName: this.$route.query.catalogTypeName,
        catalogType: this.$route.query.catalogType,
        catalogName: this.$route.query.catalogName,
        catalogId: this.$route.query.catalogId
      }
      this.init()
    },

}
</script>

<style lang="less">
.hidden-select{
    .el-input__inner{
        border: none;
        padding: 0;
    }
}

</style>

